//
//  FZStatusViewModel.swift
//  MyWeiBo
//
//  Created by fangzhengwei on 2017/3/31.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit

class FZStatusViewModel: NSObject {
//   认证类型 -1：没有认证，1，认证用户，2,3,5: 企业认证，220: 达人
    var verifiedTypeImg : UIImage?
    var mbrankImg : UIImage?
    var contentText : String?
    var sourceTxt : String?
    var createTime : String?
    var originAttributeString : NSAttributedString?
    var retweetAttributeString : NSAttributedString?
    
    var statusModel :FZStatusModel? {
        
        didSet {
            
           judgeVerifiedType(verifiedType: (statusModel?.user?.verified_type)!)
            
           judgembank(mbank: (statusModel?.user?.mbrank)!)
            
           judgeContentText(status: statusModel!)
            
           judgeSourceText(sourceText: (statusModel?.source)!)
            
           judgeCreateAt(createAt: (statusModel?.created_at)!)
           
           originAttributeString = handleEmotionAttributedString(status: (statusModel?.text)!, isorigin: true)
        }
    }
    
    var time : String {
        
        return (statusModel?.source)!
    }
    
    func judgeCreateAt(createAt : String) {
        
        let formater = DateFormatter()
        
        formater.dateFormat = "EEE MM dd HH:mm:ss z yyyy"
        
        let date = formater.date(from: createAt)
        
        guard let createDate = date else {
            return
        }
        
        //代码执行到此服务端时间转成date类型
        
        formater.dateFormat = "yyyy"
        
        //获取的年份
        let createYear = formater.string(from: createDate)
        
        //获取今年的年份
        
        let currentYear = formater.string(from: Date())
        
        let isThisYear = createYear == currentYear
        
        if isThisYear {
            //是今年
            let currentCalentor = Calendar.current
            
            if currentCalentor.isDateInToday(createDate) {
                //是今天
                let timeDifference = abs(createDate.timeIntervalSinceNow)
                
                if timeDifference < 60 {
                    //60秒以内
                    createTime = "刚刚"
                }else if timeDifference < 3600{
                    
                    let minste = Int(timeDifference / 60)
                    
                    createTime = "\(minste)分钟前"
                
                }else {
                    
                    let hours = Int(timeDifference / 3600)
                    createTime = "\(hours)小时前"
                }
                
            }else if currentCalentor.isDateInYesterday(createDate){
                //是昨天 昨天 HH:mm
                formater.dateFormat = "HH : mm"
                let createYesterday = formater.string(from: createDate)
                createTime = "昨天 \(createYesterday)"
                
            }else{
                //其他 MM-dd HH : mm
                formater.dateFormat = "MM-dd HH : mm"
                
                let others = formater.string(from: createDate)
                
                createTime = "\(others)"
            }
            
        }else{
            //不是今年
            formater.dateFormat = "yyyy-MM-dd"
            
            createTime = formater.string(from: createDate)
            
        }
        
    }
    
    
    func judgeSourceText(sourceText : String) {
        
        let startRange = sourceText.range(of: "\">")
        let endRange = sourceText.range(of: "</")
        
        let startIndex = startRange?.upperBound
        let endIndex = endRange?.lowerBound
        
        if let start = startIndex , let end = endIndex {
            
            var subString = sourceText.substring(with: start ..< end)
            
            if subString.contains("weibo.com"){
                subString = "微博"
            }
            
            sourceTxt = "来自: \(subString)"
        }
        
    }
    
    func judgeContentText(status : FZStatusModel) {
        
        let status = status.retweeted_status?.user?.screen_name
     
        let statusContent = statusModel?.retweeted_status?.text
        
        if let statusName = status , let staContent = statusContent{
            
            contentText = "@\(statusName):\(staContent)"
            
            retweetAttributeString = handleEmotionAttributedString(status: contentText!, isorigin: false)
        }
//
    }
    func judgembank(mbank : Int) {
        
        
        if mbank >= 1 && mbank <= 6{
            
            mbrankImg = UIImage(named: "common_icon_membership_level\(mbank)")
        }else{
        
            mbrankImg = UIImage(named: "common_icon_membership_expired")

        }
    }
    
    
   fileprivate func judgeVerifiedType(verifiedType: Int) {
        
        switch verifiedType {
        case 1:
            
            verifiedTypeImg = UIImage(named: "avatar_vip")
        case 2,3,5:
            
            verifiedTypeImg = UIImage(named: "avatar_enterprise_vip")
        case 220:
            
            verifiedTypeImg = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImg = nil
        }
    }
    
    
    fileprivate func handleEmotionAttributedString(status : String, isorigin : Bool) -> NSAttributedString {
      //将微博内容转换成富文本
      let attributedStr = NSMutableAttributedString(string: status)
      //匹配表情描述
      let regular = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: [])
      //匹配微博内容的表情描述
      let matchResultArr = regular.matches(in: status, options: [], range: NSMakeRange(0,(status as NSString).length))
      //倒着替换表情描述
        for matchResult in matchResultArr.reversed() {
            
            let range = matchResult.range
            let chs = (status as NSString).substring(with: range)
            
             if let emotionModel = FZEmotionViewModel.sharedEmotion.selectedEmotion(chs: chs) {
                
                let attributeString = NSAttributedString.attributeStringAccordingToEmotion(emotion: emotionModel, font: UIFont.systemFont(ofSize: 13))
        
                attributedStr.replaceCharacters(in: range, with: attributeString)
            }
            
        }
        
        if isorigin {
            
            attributedStr.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName : UIColor.darkGray], range: NSRange(location: 0, length: attributedStr.length))
            
        }else{
              attributedStr.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName : UIColor.lightGray], range: NSRange(location: 0, length: attributedStr.length))
        }
        
        
        return attributedStr
    }
    
    
}












